package com.iring.util.common;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 获取ip地址
 *
 * @author wanggan
 */
@Component
public class IPUtils {
    private static final Logger logger = LoggerFactory.getLogger(IPUtils.class);

    /**
     * 生成一个随机的ip地址
     *
     * @return ip地址
     */
    public static String getRandomIp() {
        int a = 0 * 256 * 256 + 0 * 256 + 2;
        int b = 254 * 256 * 256 + 254 * 256 + 254;
        int c = new Random().nextInt(b - a) + a;
        String ip = "10." + (c / (256 * 256)) + "." + ((c / 256) % 256) + "." + (c % 256);
        return ip;
    }

    public static String getServerIp() {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                        .getRequest();

        String serverip = null;
        serverip = request.getHeader("Referer");
        if (serverip != null && serverip.length() > 0) {
            return serverip;
        }
        serverip = request.getHeader("Origin");
        if (serverip != null && serverip.length() > 0) {
            return serverip + "/";
        }
        return serverip;
    }

    /**
     * 获取客户端ip地址
     *
     * @param request
     *            request对象
     * @return 客户端ip
     */
    public static String getClientIp(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }
        return ip;
    }

}
